const http = require('http');

function makeRequest(options, data = null) {
    return new Promise((resolve, reject) => {
        const req = http.request(options, (res) => {
            let body = '';
            res.on('data', (chunk) => body += chunk);
            res.on('end', () => {
                try {
                    const jsonBody = body ? JSON.parse(body) : {};
                    resolve({ status: res.statusCode, data: jsonBody, body });
                } catch (e) {
                    resolve({ status: res.statusCode, data: null, body });
                }
            });
        });

        req.on('error', reject);
        
        if (data) {
            req.write(data);
        }
        
        req.end();
    });
}

async function testDebugAPI() {
    console.log('🧪 测试调试服务器API...');
    
    const baseOptions = {
        hostname: 'localhost',
        port: 3001,  // 调试服务器端口
        headers: {
            'Content-Type': 'application/json'
        }
    };

    try {
        // 1. 健康检查
        console.log('\n1️⃣ 测试健康检查...');
        const healthResult = await makeRequest({
            ...baseOptions,
            path: '/health',
            method: 'GET'
        });
        
        console.log('健康检查结果:', healthResult);

        // 2. 获取歌曲列表
        console.log('\n2️⃣ 测试获取歌曲列表...');
        const songsResult = await makeRequest({
            ...baseOptions,
            path: '/api/songs',
            method: 'GET'
        });
        
        console.log('歌曲列表结果:', songsResult);

        // 3. 添加歌手
        console.log('\n3️⃣ 测试添加歌手...');
        const newSingerName = '调试测试歌手-' + Date.now();
        const addSingerResult = await makeRequest({
            ...baseOptions,
            path: '/api/songers',
            method: 'POST'
        }, JSON.stringify({ name: newSingerName }));
        
        console.log('添加歌手结果:', addSingerResult);

        // 4. 获取歌手列表
        console.log('\n4️⃣ 测试获取歌手列表...');
        const singersResult = await makeRequest({
            ...baseOptions,
            path: '/api/songers',
            method: 'GET'
        });
        
        console.log('歌手列表结果:', singersResult);

    } catch (error) {
        console.error('❌ 测试失败:', error);
    }
}

testDebugAPI().then(() => {
    console.log('\n🏁 调试测试完成');
    process.exit(0);
}).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
});